package cn.powertime.evaluation.shiro.filter;

import cn.powertime.evaluation.shiro.jwt.JwtToken;
import cn.powertime.evaluation.shiro.jwt.TokenUtils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;


/**
 * @author ZYW
 */
public class JwtAuthenticationFilter extends AuthenticatingFilter {


    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpRequest = (HttpServletRequest) request;

        String token = TokenUtils.getRequestToken(httpRequest);

        return JwtToken.builder()
                .token(token)
                .host(request.getRemoteHost())
                .build();
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //添加判断
        if(null != getSubject(request,response) && getSubject(request,response).isAuthenticated()){
            return true;
        }
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        return executeLogin(request, response);
    }

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
                                     ServletResponse response) throws Exception {
        return true;
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException ae, ServletRequest request,
                                     ServletResponse response) {
        HttpServletResponse servletResponse = (HttpServletResponse) response;
        try {
            Map<String,Object> map = new HashMap<>();
            map.put("message",ae.getCause().getMessage());
            map.put("code", 401);
            map.put("timestamp", System.currentTimeMillis());
            servletResponse.setStatus(401);
            servletResponse.setCharacterEncoding("UTF-8");
            servletResponse.setContentType("application/json;charset=UTF-8");
            servletResponse.setHeader("Access-Control-Allow-Origin","*");
            servletResponse.getOutputStream().write(JSON.toJSONString(map).getBytes());
        } catch (IOException e) {
        }
        return false;
    }

}
